package firewing.datastore;

import java.util.ArrayList;
import java.util.Iterator;

import java.util.logging.Logger;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query;

import firewing.object.Ad;

/**
 * parent_key: query, key: title, value: creative+landing_page+URL
 * 
 * @author Shuai Yuan
 * 
 */
public class AdsStore {
	private static final Logger LOG = Logger
			.getLogger(AdsStore.class.getName());

	private static DatastoreService _datastore = DatastoreServiceFactory
			.getDatastoreService();

	public static void put(String query, Ad ad) {
		Entity eQuery = new Entity("Query", query);
		Entity eAd = new Entity("Ad", eQuery.getKey());

		eAd.setProperty("Title", ad.getTitle());
		eAd.setProperty("Creative", ad.getCreative());
		eAd.setProperty("LandingPage", ad.getLandingPage());
		eAd.setProperty("URL", ad.getUrl());

		_datastore.put(eQuery);
		_datastore.put(eAd);

		LOG.info("Saving ad to datastore completed");
	}

	public static ArrayList<Ad> get(String query) {
		ArrayList<Ad> ret = new ArrayList<Ad>();

		Query qAd = new Query("Ad");
		qAd.setAncestor((new Entity("Query", query)).getKey());

		int counter = 0;

		for (Iterator<Entity> e = _datastore.prepare(qAd).asIterator(); e
				.hasNext();) {
			Entity eAd = e.next();
			Ad ad = new Ad();
			ad.setTitle((String) eAd.getProperty("Title"));
			ad.setCreative((String) eAd.getProperty("Creative"));
			ad.setLandingPage((String) eAd.getProperty("LandingPage"));
			ad.setUrl((String) eAd.getProperty("URL"));

			ret.add(ad);

			counter++;
		}

		LOG.info("Datastore returned " + counter + " ads");

		return ret;
	}
}
